<template>
  <el-dialog
    v-model="dialogVisible"
    title="采样/测量地点设置示意图"
    width="50%"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="equipment-layout-container1">
      <div class="1header-actions">
        <el-button type="primary" @click="handleAddRow">添加示意图</el-button>
      </div>

      <el-table :data="equipmentLayoutList" border style="width: 100%">
        <el-table-column align="center" width="350">
          <template #header>
            <span>工作场所</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.workplace"
              allow-create
              filterable
              multiple
              placeholder="请选择或输入工作场所"
              style="width: 100%"
              @visible-change="(v: boolean) => v && loadWorkshopOptions(3)"
              @change="handleWorkshopChange"
            >
              <el-option
                v-for="workshop in workshopOptions"
                :key="workshop"
                :label="workshop"
                :value="workshop"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center">
          <template #header>
            <span>设备布局图</span>
          </template>
          <template #default="scope">
            <div class="image-upload-container">
              <el-upload
                :auto-upload="false"
                :on-change="(file) => handleEquipmentLayoutImageUpload(file.raw!, scope.$index)"
                :show-file-list="false"
                accept="image/*"
                class="image-uploader"
                multiple
              >
                <el-button type="primary">上传图片</el-button>
              </el-upload>
              <div class="image-list">
                <div
                  v-for="(image, imageIndex) in scope.row.layoutImages"
                  :key="imageIndex"
                  class="image-item"
                >
                  <el-image
                    :initial-index="imageIndex"
                    :preview-src-list="scope.row.layoutImages"
                    :src="image"
                    class="preview-image"
                    fit="cover"
                    hide-on-click-modal
                    preview-teleported
                  />
                  <el-button
                    class="delete-button"
                    size="small"
                    type="danger"
                    @click="handleEquipmentLayoutImageRemove(scope.$index, imageIndex)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="danger" @click="handleEquipmentLayoutDelete(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { UploadRawFile } from 'element-plus'
import { ProjectApi } from '@/api/dk/project'
import { useUpload } from '@/components/UploadFile/src/useUpload'

// 接口定义
interface EquipmentLayoutItem {
  workplace: string[]
  layoutImages: string[]
}

// Props 定义
interface Props {
  visible: boolean
  projectId: string
  data?: EquipmentLayoutItem[]
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  data: () => []
})

// Emits 定义
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'confirm': [data: EquipmentLayoutItem[]]
}>()

// 响应式数据
const route = useRoute()
const { httpRequest } = useUpload()
const dialogVisible = ref(false)
const equipmentLayoutList = ref<EquipmentLayoutItem[]>([])
const workshopOptions = ref<string[]>([])
const workshopOptionsCache = ref<Record<number, string[]>>({})

// 监听 visible 变化
watch(
  () => props.visible,
  async (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      // 调用 getJobSurveySketch 获取数据
      await getJobSurveySketch()
    }
  },
  { immediate: true }
)

const getJobSurveySketch = async () => {
  try {
    const jobSurveySketch = await ProjectApi.getJobSurveySketch(props.projectId)
    console.log('获取工作方案草稿成功:', JSON.stringify(jobSurveySketch))
    if (jobSurveySketch && jobSurveySketch.jobSurvey && Array.isArray(jobSurveySketch.jobSurvey)) {
      // 将获取到的数据填充到 equipmentLayoutList 中
      equipmentLayoutList.value = [...jobSurveySketch.jobSurvey]
    }
  } catch (error) {
    console.error('获取工作方案草稿失败:', error)
    ElMessage.error('获取工作方案草稿失败')

  }
}

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 加载工作车间选项
const loadWorkshopOptions = async (type: number) => {
  try {
    const data = await ProjectApi.getWorkShopPositionName(Number(route.query.projectId), type)
    console.log('获取工作车间/岗位数据成功:', { type, data })

    if (data && Array.isArray(data)) {
      // 确保数据去重
      const uniqueData = Array.from(new Set(data))
      workshopOptionsCache.value[type] = uniqueData

      // 只更新当前类型的选项，不合并其他类型的数据
      workshopOptions.value = [...uniqueData]
      return true
    }
    return false
  } catch (error) {
    console.error('获取工作车间/岗位数据失败:', error)
    ElMessage.error('获取工作场所数据失败')
    throw error
  }
}

// 处理工作车间变化
const handleWorkshopChange = () => {
  // 工作车间变化时的处理逻辑
  console.log('工作车间发生变化')
}

// 添加新行
const handleAddRow = () => {
  equipmentLayoutList.value.push({
    workplace: [],
    layoutImages: []
  })
}

// 处理设备布局图片上传
const handleEquipmentLayoutImageUpload = async (file: UploadRawFile, rowIndex: number) => {
  try {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 创建 UploadRawFile
    const rawFile: UploadRawFile = Object.assign(file, {
      uid: Date.now()
    })

    // 使用 useUpload 上传文件
    const result = await httpRequest({
      file: rawFile,
      filename: file.name,
      data: {},
      headers: {},
      action: '',
      method: 'post',
      onProgress: () => {},
      onError: () => {},
      onSuccess: () => {},
      withCredentials: false
    })

    if (result && typeof result === 'object' && 'data' in result) {
      // 将返回的URL添加到图片列表中
      if (!equipmentLayoutList.value[rowIndex].layoutImages) {
        equipmentLayoutList.value[rowIndex].layoutImages = []
      }
      equipmentLayoutList.value[rowIndex].layoutImages.push(result.data as string)
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  return false
}

// 删除设备布局图片
const handleEquipmentLayoutImageRemove = (rowIndex: number, imageIndex: number) => {
  if (equipmentLayoutList.value[rowIndex]?.layoutImages) {
    equipmentLayoutList.value[rowIndex].layoutImages.splice(imageIndex, 1)
  }
}

// 删除设备布局行
const handleEquipmentLayoutDelete = (index: number) => {
  equipmentLayoutList.value.splice(index, 1)
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

// 确认
const handleConfirm = async () => {
  // 验证数据
  const hasError = equipmentLayoutList.value.some(item => {
    return !item.workplace?.length || !item.layoutImages?.length
  })

  if (hasError) {
    ElMessage.error('请完善所有必填项!')
    return
  }

  try {
    console.log('设备布局数据:{}', JSON.stringify(equipmentLayoutList.value))
    const data = {
      "projectId": props.projectId,
      "jobSurvey": equipmentLayoutList.value
    }
    console.log('result:{}', JSON.stringify(data))
    await ProjectApi.updateJobSurveySketch(data)
    ElMessage.success('保存成功')
    handleClose()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 组件卸载时清理
const cleanup = () => {
  // 清理逻辑（如果需要的话）
}

// 暴露清理方法
defineExpose({
  cleanup
})
</script>

<style scoped lang="scss">
.equipment-layout-container {
  .header-actions {
    margin-bottom: 16px;
    text-align: right;
  }

  .required-star {
    color: #f56c6c;
    margin-left: 4px;
  }

  .image-upload-container {
    .image-uploader {
      margin-bottom: 12px;
    }

    .image-list {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;

      .image-item {
        position: relative;
        display: inline-block;

        .preview-image {
          width: 80px;
          height: 80px;
          border-radius: 6px;
          cursor: pointer;
          border: 1px solid #dcdfe6;
        }

        .delete-button {
          position: absolute;
          top: -8px;
          right: -8px;
          min-height: 24px;
          padding: 2px 6px;
          border-radius: 12px;
          font-size: 12px;
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 全局样式覆盖
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-table) {
  .el-table__cell {
    vertical-align: middle;
  }
}

:deep(.el-upload) {
  .el-button {
    margin-bottom: 0;
  }
}
</style>
